﻿using Coldairarrow.Util;

using GCC.Container.Models;
using GCC.APIContainer.Utilities;
using Microsoft.AspNetCore.Mvc;
using tcm.Filters;
using tcm.request;
using GCC.Container.Abstracts;
using tcm.entity;
using tcm.entity.Device;
using tcm.request.Device;
using tcm.utils;
using System.Text;

namespace tcm.Controller
{
    [ApiController]//记住这个单词
    [Route("tcm/cabinet")]//记住这个
    public class CabinetController : GCCAPIControllerBase
    {
        private readonly AbsGCCContext _context;
        public CabinetController(AbsGCCContext context) : base(context)
        {
            _context = context;
        }

        #region 药柜管理
        /// <summary>
        /// 查询药柜列表
        /// </summary>
        /// <returns></returns>
        [HttpGet("getlist")]
        [TCMAuth(permission: "equipment:cabinet:list")]
        public DataResponse<List<CabinetSelect>> GetList([FromQuery] CabinetRequest request)
        {
            var sql = new StringBuilder();

            _=sql.Append("select c.*,pl.list_name as phm_list_name,s.id as site_id, s.site_name " +
                        "from tcm_cabinet c " +
                        "left join tcm_phm_list pl on pl.id=c.phm_list_id " +
                        "left join tcm_device d on d.id=c.device_id " +
                        "left join tcm_site s on s.id=d.site_id " +
                        "where 1=1 ");

            if (request.device_id>0)
                _=sql.Append(string.Format(" and c.device_id = {0}", request.device_id));
            if(request.site_id>0)
                _=sql.Append(string.Format(" and s.id = {0}", request.site_id));
            if (request.start_date!=null)
                _=sql.Append(string.Format(" and c.create_date >= '{0}' ", request.start_date));
            if (request.end_date!=null)
                _=sql.Append(string.Format(" and c.create_date <=  '{0}' ", request.end_date));

            _=sql.Append(" order by c.create_date desc  ");
            var dbres = GCCEntrance.DBManager!.LocalDB!.Select<CabinetSelect>()
                .WithSql(sql.ToString())
               .Count(out var count)
               .Page(request.PageIndex ?? 1, request.PageSize!=0 ? request.PageSize : int.MaxValue)
               .ToList();

            foreach (var item in dbres)
            {
                var sqlstr = new StringBuilder();
                _=sqlstr.Append(string.Format("select pl.phm_list_id,pl.phm_num,p.*,pl.phm_num*{0} as phm_total from  tcm_phm_list_relation pl join tcm_pharmaceutical p on  pl.phm_id= p.id", item.num));
                _=sqlstr.Append(string.Format(" where pl.phm_list_id = '{0}' ", item.phm_list_id));
                var pharmaceuticalInfos = GCCEntrance.DBManager!.LocalDB!.Select<PharmaceuticalInfo>()
                    .WithSql(sqlstr.ToString())
                   .ToList();
                item.pharmaceuticals.AddRange(pharmaceuticalInfos);
            }
            return HandleData(dbres, count);
        }

        /// <summary>
        /// 查询药柜详情
        /// </summary>
        /// <returns></returns>
        [HttpGet("get/{id}")]
        public DataResponse<CabinetSelect> GetCabinet([FromRoute] long id)
        {
            var sql = new StringBuilder();
            _=sql.Append("select c.*,pl.list_name as phm_list_name,s.id as site_id, s.site_name " +
                          "from tcm_cabinet c " +
                          "left join tcm_phm_list pl on pl.id=c.phm_list_id " +
                          "left join tcm_device d on d.id=c.device_id " +
                          "left join tcm_site s on s.id=d.site_id " +
                          "where c.id="+id);

            var dbres = GCCEntrance.DBManager!.LocalDB!.Select<CabinetSelect>()
              .WithSql(sql.ToString())
             .First();

            var sqlstr = new StringBuilder();
            _=sqlstr.Append(string.Format("select pl.phm_list_id,pl.phm_num,p.*,pl.phm_num*{0} as phm_total from  tcm_phm_list_relation pl join tcm_pharmaceutical p on  pl.phm_id= p.id", dbres.num));
            _=sqlstr.Append(String.Format(" where pl.phm_list_id = '{0}' ",  dbres.phm_list_id));
            var pharmaceuticalInfos = GCCEntrance.DBManager!.LocalDB!.Select<PharmaceuticalInfo>()
                .WithSql(sqlstr.ToString())
               .ToList();

            dbres.pharmaceuticals.AddRange(pharmaceuticalInfos);

            //var res = GCCEntrance.DBManager!.LocalDB!.Queryable<Cabinet>().Where(x => x.id==id).First();
            return HandleData(dbres);
        }


        /// <summary>
        /// 添加药柜
        /// </summary>
        /// <returns></returns>
        [HttpPost("add")]
        [TCMAuth(permission: "equipment:cabinet:add")]
        public DataResponse<bool> AddCabinet([FromBody] CabinetDto request)
        {
            var saveRes = false;

            try
            {
                var isExists = GCCEntrance.DBManager!.LocalDB!.Select<Cabinet>()
                    .Where(x => x.cabinet_no==request.cabinet_no&&x.device_id==request.device_id)
                    .Any();
                if(isExists)
                    throw new Exception("货柜编号已存在");

                GCCEntrance.DBManager!.LocalDB!.Transaction(() =>
                {
                    request.Create(_context, HttpContext.GetToken()).Wait();
                    Cabinet cabinet = BeanUtils.copy<Cabinet, CabinetDto>(request);
                    if (GCCEntrance.DBManager!.LocalDB!.Insert(cabinet).ExecuteAffrows() != 1)
                    {
                        throw new Exception();
                    }
                    saveRes=true;
                });
            }
            catch (Exception exe)
            {
                return SystemError<bool>("新增异常："+exe.Message);
            }

            return HandleData(saveRes);
        }

        /// <summary>
        /// 更新药柜
        /// </summary>
        /// <returns></returns>
        [HttpPost("update")]
        [TCMAuth(permission: "equipment:cabinet:update")]
        public DataResponse<bool> UpdateCabinet([FromBody] CabinetDto request)
        {
            var saveRes = false;
            if (request.id<=0)
                return SystemError<bool>("id为空");
            try
            {
                var isExists = GCCEntrance.DBManager!.LocalDB!.Select<Cabinet>()
                    .Where(x => x.cabinet_no==request.cabinet_no&& x.id!= request.id&&x.device_id==request.device_id)
                    .Any();
                if (isExists)
                    throw new Exception("货柜编号已存在");

                GCCEntrance.DBManager!.LocalDB!.Transaction(() =>
                {

                    var cabinet = GCCEntrance.DBManager.LocalDB.Select<Cabinet>().Where(a => a.id == request.id).First();
                    if (cabinet==null)
                        throw new Exception("药柜不存在");
                    request.create_by = cabinet.create_by;
                    request.create_date = cabinet.create_date;
                    request.Modify(_context, HttpContext.GetToken()).Wait();

                    BeanUtils.copy<Cabinet, CabinetDto>(request, ref cabinet);

                    if (GCCEntrance.DBManager.LocalDB.Update<Cabinet>(request.id).SetSource(cabinet).ExecuteAffrows()<=0)
                    {
                        throw new Exception();
                    }

                    saveRes=true;
                });
            }
            catch (Exception exe)
            {
                return SystemError<bool>("更新异常："+exe.Message);
            }
            return HandleData(saveRes);
        }

        /// <summary>
        /// 删除药柜
        /// </summary>
        /// <returns></returns>
        [HttpDelete("delete/{ids}")]
        [TCMAuth(permission: "equipment:cabinet:delete")]
        public DataResponse<bool> DeleteDevice([FromRoute] string ids)
        {
            var saveRes = false;
            if (string.IsNullOrWhiteSpace(ids))
                return SystemError<bool>("id为空");

            var idList = SysHelper.SpitIntArrary(ids);
            var msg = new StringBuilder();
            foreach (var id in idList)
            {
                var dbquery = GCCEntrance.DBManager.GlobalDB.Select<Order, Cabinet, Device>()
               .InnerJoin((a, c, e) => a.cabinet_id == c.id)
               .InnerJoin((a, c, e) => c.device_id == e.id)
               .Where((a, c, e) => a.status!= 1 && id == c.id)
               .ToList();

                if (dbquery!=null &&  dbquery.Count> 0)
                    _=msg.Append(id+"；");
            }
            if (!string.IsNullOrWhiteSpace(msg.ToString()))
            {
                return SystemError<bool>("药柜已在使用不可删除。删除id："+msg.ToString());
            }


            saveRes = GCCEntrance.DBManager!.LocalDB!.Delete<Cabinet>().Where(x => idList.Contains(x.id)).ExecuteAffrows()>0;

            return HandleData(saveRes);
        }

        #endregion

        [HttpGet("query")]
        public DataResponse<List<Cabinet>> query([FromQuery] CabinetQueryReq req)
        {
            List<Cabinet> list = GCCEntrance.DBManager.GlobalDB.Select<Cabinet>()
                .WhereIf(req.device_id != null, a => a.device_id == req.device_id)
                .WhereIf(!String.IsNullOrEmpty(req.cabinet_no), a => a.cabinet_no == req.cabinet_no)
                .WhereIf(req.phm_list_id != null, a => a.phm_list_id == req.phm_list_id)
                .WhereIf(req.is_have != null, a => a.is_have == req.is_have)
                .WhereIf(req.is_use == 0, a => a.is_use == 0 || a.is_use == null)
                .WhereIf(req.is_use == 1, a => a.is_use == 1)
                .OrderByDescending(a => a.create_date).ToList();

            return HandleData(list);
        }

        [HttpGet("queryCabinet")]
        public DataResponse<List<Cabinet>> queryCabinet(long? phm_list_id, long? site_id, long? cabinet_id, long? device_id, int? is_use)
        {
            var query = GCCEntrance.DBManager.GlobalDB.Select<Cabinet, Device, Site>()
                .InnerJoin((a, b, c) => a.device_id == b.id)
                .InnerJoin((a, b, c) => b.site_id == c.id)
                .Where((a, b, c) => b.type == 2)
                .WhereIf(is_use == 0, (a, b, c) => a.is_use == 0 || a.is_use == null)
                .WhereIf(is_use == 1, (a, b, c) => a.is_use == 1)
                .WhereIf(cabinet_id != null, (a, b, c) => a.id == cabinet_id)
                .WhereIf(device_id != null, (a, b, c) => b.id == device_id);


            if (phm_list_id.HasValue)
            {
                query=query.Where((a, b, c) => a.phm_list_id==phm_list_id.Value);
            }
            if (site_id.HasValue)
            {
                query=query.Where((a, b, c) => c.id == site_id.Value);
            }

            var list = query.OrderByDescending((a, b, c) => a.create_date).ToList();

            return HandleData(list);
        }
    }
}
